from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import datetime
from selenium.common.exceptions import NoSuchElementException

driver = webdriver.Chrome()


def login():
    url1 = 'https://account.xiaomi.com/'
    url2 = 'https://www.mi.com/seckill/'
    print('访问网址···')
    driver.get(url1)
    print('登录中···')
    driver.find_element_by_id("username").send_keys('17620533205')
    driver.find_element_by_id("pwd").send_keys('531109an')
    driver.find_element_by_id("login-button").click()
    print('登录成功···')
    time.sleep(1)
    print('进入小米秒杀界面等待秒杀···')
    driver.get(url2)


def buy_on_time(buytime):
    while True:
        start_time = time.strftime('%Y-%m-%d %H:%M:%S')
        if start_time > buytime:
            print(start_time, '开始秒杀！')
            driver.refresh()
            driver.find_element_by_xpath("/html/body/div[3]/div[2]/div[2]/span/ul[1]/li[4]/a/span[2]/span[5]").click()
            btn1 = driver.find_element_by_xpath('/html/body/div[4]/div/div[2]/div[2]/div[2]/ul/li[1]/a')
            if btn1:
                btn1.click()
                driver.find_element_by_xpath('/html/body/div[3]/div/div[1]/div[2]/a[2]')
            else:
                driver.get('https://www.mi.com/seckill/')
                buy_on_time(buytime)
            btn = driver.find_element_by_xpath('/html/body/div[14]/div[3]/div/button[2]')
            time.sleep(0.5)
            if btn:
                btn.click()
                time.sleep(0.5)
                driver.find_element_by_xpath("/html/body/div[3]/div[2]/div[2]/span/ul[1]/li[3]/a/span[2]/span[5]").click()
                driver.find_element_by_xpath("/html/body/div[4]/div/div[2]/div[2]/div[2]/ul/li[1]/a").click()
            else:
                driver.find_element_by_xpath("/html/body/div[4]/div/div[2]/div[2]/div[2]/ul/li[1]/a").click()
            driver.get('https://static.mi.com/cart/')
            driver.find_element_by_xpath("/html/body/div[2]/div/div[3]/div[4]/a").click()
            driver.find_element_by_xpath("/html/body/div[2]/div/div/div[1]/div[2]/div[1]").click()
            print('检测到有库存，正在下单，请稍等···')
            driver.find_element_by_xpath("/html/body/div[2]/div/div/div[8]/div[2]/a[1]").click()
            over_time = time.strftime('%Y-%m-%d %H:%M:%S')
            print(over_time, '秒杀结束！')
            print('下单成功，请抓紧付款！')
            break
        time.sleep(0.01)


login()
buy_on_time('2019-09-12 18:23:00')
